/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package customTags;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Stack;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 *
 * @author ToanNhan
 */
public class GetTag extends SimpleTagSupport {

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    /**
     * Called by the container to invoke this tag. 
     * The implementation of this method is provided by the tag library developer,
     * and handles all tag processing, body iteration, etc.
     */
    @Override
    public void doTag() throws JspException {
        Stack stack = (Stack) this.getJspContext().getAttribute(AttributeUtil.templateStack, PageContext.REQUEST_SCOPE);
        if (stack == null) {
            throw new JspException("GetTag.doTag() : NO STACK");
        }

        Hashtable params = (Hashtable) stack.peek();
        if (params == null) {
            throw new JspException("GetTag.doTag() : NO HASHTABLE");
        }
        ArrayList<PageParameter> arr = (ArrayList<PageParameter>) params.get(name);
        if (arr != null) {
            JspWriter out = getJspContext().getOut();
            try {
                for (PageParameter param : arr) {
                    if (param.isDirect()) {
                        out.print(param.getContent());
                    } else {
                        out.flush();
                        PageContext page = (PageContext) this.getJspContext();
                        page.include(param.getContent());
                    }
                }
                JspFragment f = getJspBody();
                if (f != null) {
                    f.invoke(out);
                }

                // TODO: insert code to write html after writing the body content.
                // e.g.:
                //
                // out.println("    </blockquote>");

            } catch (java.io.IOException ex) {
                throw new JspException("Error in GetTag tag", ex);
            } catch (ServletException ex) {
                Logger.getLogger(GetTag.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
